package com.swdegao.iot.netty.controller;

import com.alibaba.fastjson.JSONObject;
import com.swdegao.iot.netty.entity.ServerResponse;
import com.swdegao.iot.netty.mqtt.MqttPushClient;
import com.swdegao.iot.netty.server.qianbaotongplushandler.QianBaoTongPlus_Const;
import com.swdegao.iot.netty.service.CMDService;
import com.swdegao.iot.netty.service.MqttCommandService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * 电磁水表、流量计设备命令下发入口
 */
@RestController
@RequestMapping("/terminalCommand")
@Slf4j
public class TerminalCommandController {

	@Autowired
	public CMDService cmd;

	@Resource
	private MqttPushClient mqttPushClient;// mqtt推送端

	@Autowired
	private MqttCommandService mqttCommandService;// 德高MQTT服务

   /**
    * 获取当前连接数
    * @return 连接个数
    */
   @RequestMapping(value = "/get_channel_size",method = RequestMethod.GET)
   @ResponseBody
   public ServerResponse<Integer> getChannelSize(){
       return ServerResponse.createBySuccess(QianBaoTongPlus_Const.getSzie());
   }

   /**
    * 获取连接Id数组
    * @return Id数组
    */
   @RequestMapping(value = "/get_channel_id_list",method = RequestMethod.GET)
   @ResponseBody
   public ServerResponse<Set<String>> getChannelIDList(){
       return ServerResponse.createBySuccess(QianBaoTongPlus_Const.getIdList());
   }

   /**
    * 获取设备的连接状态
    * @return Id数组
    */
   @RequestMapping(value = "/get_channel_status",method = RequestMethod.POST)
   @ResponseBody
   public ServerResponse<String> getChannelIDStatus(String channelId){
   	String status = QianBaoTongPlus_Const.getChannelStatus(channelId);
   	if("1".equals(status)){
   		return ServerResponse.createBySuccessOnLine();
   	}else{
   		return ServerResponse.createByErrorNotLine();
   	}

   }
//    /**
//     * 向存在链接发送指定的端口
//     * @param channelId 连接ID
//     * @param lock 打开第几把锁
//     * @return
//     */
//    @RequestMapping(value = "/send_to_channel",method = RequestMethod.POST)
//    @ResponseBody
//    public ServerResponse<?> SendToChannel(String channelId,String command){
//        SendUtil sendUtil = new SendUtil();
//        Channel channel = Const.get(channelId);
//        if (channel != null && channel.isActive() && command != null && !"".equals(command)){
//        	log.info("SendToChannel，获取Channel"+channel.toString());
//            if (sendUtil.send(channelId,channel,command)){
//                return ServerResponse.createBySuccessOnLine();
//            }
//        }else {
//			log.info("SendToChannel，wei获取Channel"+channel.toString());
//		}
//        return ServerResponse.createByErrorNotLine();
//    }
   /**
	 * 命令下发接口
	 * @param imei
	 * @param data
	 * @param checkflag
	 * @return
	 * @throws Exception
	 * @throws ParseException
	 */
	@ApiOperation(value="命令下发")
	@PostMapping("/commandIssued")
   public JSONObject commandIssued(@ApiParam(name = "imei", value = "表身号")@RequestParam(value="imei", required = false) String  imei,
									@ApiParam(name = "data", value = "数据体")@RequestParam(value="data", required = false) String  data,
									@ApiParam(name = "communicationType", value = "通讯类型")@RequestParam(value="communicationType", required = false) String  communicationType) throws ParseException, Exception {
		JSONObject result = cmd.commandIssued(imei, data,communicationType);
		return result;
   }

	/**
	 * 命令响应接口
	 * @param imei
	 * @param requestID
	 * @return
	 */
	@ApiOperation(value="命令响应")
	@PostMapping("/commandResponse")
	public List<JSONObject> commandResponse(@ApiParam(name = "imei", value = "表身号")@RequestParam(value="imei", required = false) String  imei,
											@ApiParam(name = "requestID", value = "请求ID")@RequestParam(value="requestID", required = false) String  requestID) {
		List<JSONObject> result = cmd.commandResponse(imei, requestID);

		return result;
	}
//
//	 /**
//		 * 命令下发接口
//		 * @param imei
//		 * @param data
//		 * @param checkflag
//		 * @return
//		 * @throws Exception
//		 * @throws ParseException
//		 */
//		@ApiOperation(value="预置命令接受")
//		@PostMapping("/waitingPresetCommand")
//	    public JSONObject waitingPresetCommand(@ApiParam(name = "imei", value = "表身号")@RequestParam(value="imei", required = false) String  imei,
//										@ApiParam(name = "data", value = "数据体")@RequestParam(value="data", required = false) String  data) throws ParseException, Exception {
//			JSONObject result = cmd.waitingPresetCommand(imei, data);
//			return result;
//	    }
//
//	    /**
//		 * 命令响应接口
//		 * @param imei
//		 * @param requestID
//		 * @return
//		 */
//		@ApiOperation(value="预置命令结果查询")
//		@PostMapping("/waitingPresetCommandResponse")
//		public List<JSONObject> waitingPresetCommandResponse(@ApiParam(name = "imei", value = "表身号")@RequestParam(value="imei", required = false) String  imei,
//												@ApiParam(name = "requestID", value = "请求ID")@RequestParam(value="requestID", required = false) String  requestID) {
//			List<JSONObject> result = cmd.commandResponse(imei, requestID);
//
//			return result;
//		}

	/**
	 * 只对MQTT模式进行处理，数据内容已经在admin模块通过协议id进行封装好，
	 * @param imei
	 * @param communicationType 6 代表德高服务器上的mqtt程序，对应设备档案表中的通讯类型字段
	 * @param msg 封装好的数据，此处直接发布，不做数据包装
	 * @param topic 对应 设备表 communication_config，后期可做拓展，发布到多个topic，用“，”分隔
	 * @return
	 */
	@ApiOperation(value="大表命令下发")
	@RequestMapping("/mqttCommandPush")
	public JSONObject mqttCommandPush(@ApiParam(name = "imei", value = "表身号")@RequestParam(value="imei", required = false) String  imei,
								  @ApiParam(name = "communicationType", value = "请求类型")@RequestParam(value="communicationType", required = false) int  communicationType,
								  @ApiParam(name = "msg", value = "主题")@RequestParam(value="msg", required = false) String msg,
									  @ApiParam(name = "topic", value = "主题")@RequestParam(value="topic", required = false) String topic

	) {
		switch(communicationType){
			case 6:
				//DeGao-MQTT：德高自有MQTT服务，6 对应数据字典value值
				JSONObject res = mqttCommandService.mqttPublish(0, false, topic, msg);// 执行消息发布
				return res;
			default:
				return null;

		}
	}




}
